using System;
using System.Collections.Generic;
using System.Configuration;
using Close.io.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Close.io.API
{
	public static class UserManager
	{
		private const string EndPoint = "organization";
		private static readonly Dictionary<string, string> _userIdDictionary;
		private static readonly Dictionary<string, string> _userNameDictionary;
		private static readonly Dictionary<string, string> _userEmailDictionary;

		static UserManager()
		{
			_userNameDictionary = new Dictionary<string, string>();
			_userIdDictionary = new Dictionary<string, string>();
			_userEmailDictionary = new Dictionary<string, string>();

			string id = ConfigurationManager.AppSettings["OrganizationId"];
			var client = new CloseIoClient();
			CloseIoApiResult response = client.Get(EndPoint, id);
			var responseObject = JsonConvert.DeserializeObject<JObject>(response.Content);
			var users = responseObject["memberships"].ToObject<JArray>();

			foreach (JObject user in users.Children<JObject>())
			{
				string userId = user["user_id"].ToString();
				string userName = user["user_full_name"].ToString();
				string userEmail = user["user_email"].ToString();
				_userNameDictionary.Add(userName, userId);
				_userIdDictionary.Add(userId, userName);
				_userEmailDictionary.Add(userId, userEmail);
			}
		}


		public static string GetUserEmailFromId(string id)
		{
			if (id == null) throw new ArgumentNullException("id");
			string userEmail;

			_userEmailDictionary.TryGetValue(id, out userEmail);

			return userEmail;
		}

		public static string GetUserNameFromId(string id)
		{
			if (id == null) throw new ArgumentNullException("id");
			string userName;
			_userIdDictionary.TryGetValue(id, out userName);

			return userName;
		}

		public static string GetUserIdFromName(string userName)
		{
			string userId;
			_userNameDictionary.TryGetValue(userName, out userId);

			return userId;
		}

		public static IEnumerable<string> GetAllUsersIds()
		{
			return _userIdDictionary.Values;
		}
	}
}